import { OnInit, Component, ViewChild, Input } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { ConsolidatedResultsDTO } from 'src/app/project/model/icm/icm-student-academic/consolidated-results/consolidated-results.dto';
import { ObjectUtil } from 'src/app/project/utils/object-util';
import { TABLE_PARAMETER } from '../../setting/table-parameter';
import { STColumn, XlsxService, STColumnBadge, STColumnTag } from '@delon/abc';
import { StatisticalAnalysisService } from 'src/app/project/service/icm/dashboard/statistical-analysis.service';
import { format } from 'date-fns';
import { ConfigurationService } from 'src/app/project/service/icm/icm-global/configuration/configuration.service';
import { NotificationInformationDetailComponent } from '../notification-information/notification-information-detail.component';

const TAG: STColumnTag = {
  1: { text: '达优', color: 'green' },
  2: { text: '未达标', color: 'red' },
  3: { text: '良好', color: '' },
  4: { text: '预警', color: 'orange' },
};
@Component({
  selector: 'app-consolidated-results-list',
  templateUrl: './consolidated-results-list.component.html',
  styles: [],
})
export class ConsolidatedResultsListComponent implements OnInit {
  constructor(
    private msg: NzMessageService,
    private statisticalAnalysisService: StatisticalAnalysisService,
    private xlsx: XlsxService,
    private configurationService: ConfigurationService,
  ) {}

  @ViewChild('notificationInformationDetailComponent', { static: false })
  notificationInformationDetailComponent: NotificationInformationDetailComponent;
  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'id,asc',
  };

  /**
   * 查询参数
   */
  @Input()
  queryParams;

  /**
   * 请求数据标识
   */
  loading = false;
  /**
   * 综合成绩统计参数
   */
  consolidateParams = {
    standard: null,
    notStandard: null,
    earlyWarningDown: null,
    earlyWarningUp: null,
  };
  /**
   * 表格数据
   */
  tableData: Array<ConsolidatedResultsDTO> = [];

  /**
   * 列表参数
   */
  TABLE_PARAMETER = ObjectUtil.deepClone(TABLE_PARAMETER);

  /**
   * 表格的列定义
   */
  stColumns: STColumn[] = [
    {
      title: '序号',
      render: 'number',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '学号',
      index: 'studentCode',
      width: '10%',
      className: 'text-left',
    },
    {
      title: '姓名',
      index: 'studentName',
      width: '8%',
      className: 'text-left',
    },
    {
      title: '综合成绩',
      render: 'consolidatedResult',
      width: '5%',
      className: 'text-right',
    },
    {
      title: '情况',
      index: 'tag',
      width: '5%',
      type: 'tag',
      tag: TAG,
      className: 'text-center',
    },
    {
      title: '学院',
      index: 'academyName',
      width: '10%',
      className: 'text-left',
    },
    {
      title: '专业',
      index: 'professionName',
      width: '10%',
      className: 'text-left',
    },
    {
      title: '班级',
      index: 'className',
      width: '10%',
      className: 'text-left',
    },
    {
      title: '性别',
      index: 'gender',
      width: '4%',
      className: 'text-center',
      format(item) {
        return item.gender === 'MALE' ? '男' : '女';
      },
    },
    {
      title: '年级',
      index: 'grade',
      width: '5%',
      className: 'text-center',
      format(item) {
        return item.grade + '级';
      },
    },
    {
      title: '测评年份',
      index: 'year',
      width: '5%',
      className: 'text-center',
      format(item) {
        return item.year + '年';
      },
    },
    {
      title: '操作',
      render: 'operations',
      index: 'operation',
      width: '10%',
      className: 'text-center',
    },
  ];

  /**
   * 表格变化事件，用于双击、排序，翻页等操作
   * @param e event
   */
  change(e: any): void {
    // 双击事件
    if (e.type === 'dblClick') {
      //   this.loading = true;
      //   // tslint:disable-next-line: deprecation
      //   this.statisticalAnalysisService.findById(e.dblClick.item.id).subscribe(
      //     data => {
      //       this.studentDetailComponent.edit(true, data);
      //     },
      //     null,
      //     () => {
      //       this.loading = false;
      //     },
      //   );
    }
    // 排序事件
    if (e.type === 'sort') {
      if (e.sort.map) {
        const temp = e.sort.map.sort;
        if (temp) {
          this.queryOptions.sort = temp.replace(/[\.-]/g, ',');
        }
      }
      this.loadData();
    }
    // 翻页设置
    if (e.type === 'ps' || e.type === 'pi') {
      this.queryOptions.page = e.pi - 1;
      this.queryOptions.size = e.ps;
      this.loadData();
    }
  }
  download() {
    const data = [this.stColumns.map(i => i.title)];
    this.tableData.forEach(i => data.push(this.stColumns.map(c => i[c.index as string])));
    this.xlsx.export({
      sheets: [
        {
          data,
          name: 'sheet name',
        },
      ],
    });
  }
  /**
   * 获取班级数据
   */
  loadData() {
    this.loading = true;
    this.statisticalAnalysisService
      .findOnePage(
        this.queryOptions,
        this.queryParams.academyId,
        this.queryParams.professionId,
        this.queryParams.classId,
        this.queryParams.studentName,
        this.queryParams.year !== '' ? format(this.queryParams.year, 'YYYY') : '',
      )
      // tslint:disable-next-line: deprecation
      .subscribe(
        data => {
          if (data) {
            this.tableData = data.data;
            this.tableData.forEach(badge => {
              badge.tag =
                badge.consolidatedResult > this.consolidateParams.standard
                  ? 1
                  : badge.consolidatedResult < this.consolidateParams.notStandard
                  ? 2
                  : badge.consolidatedResult > this.consolidateParams.earlyWarningDown &&
                    badge.consolidatedResult < this.consolidateParams.earlyWarningUp
                  ? 4
                  : 3;
            });
            this.TABLE_PARAMETER.page.total = data.totalRecords;
          }
        },
        null,
        () => {
          this.loading = false;
        },
      );
  }

  /**
   * 发通知
   * @param row 数据
   */
  createNotification(row: ConsolidatedResultsDTO) {
    this.notificationInformationDetailComponent.create(row.studentId, row.studentName);
  }

  /**
   * 初始化规则
   */
  loadRule() {
    // 获得达优分
    this.configurationService.findById('7').subscribe(data => {
      this.consolidateParams.standard = data.value;
    });
    // 获得达标分
    this.configurationService.findById('8').subscribe(data => {
      this.consolidateParams.notStandard = data.value;
    });
    // 获得预警区间下限分
    this.configurationService.findById('9').subscribe(data => {
      this.consolidateParams.earlyWarningDown = data.value;
    });
    // 获得预警区间上限分
    this.configurationService.findById('10').subscribe(data => {
      this.consolidateParams.earlyWarningUp = data.value;
    });
  }
  ngOnInit() {
    this.loadRule();
    setTimeout(() => {
      this.loadData();
    }, 2000);
  }
}
